<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 文件上传 MD5 重命名
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: md5.php 187 2012-05-04 01:37:01Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Upload_MD5 extends Upload_Rename
{

    /**
     * 目录级数
     *
     * @var int
     */
    public static $level = 1;

    /**
     * 设置参数
     *
     * @param  string  $path
     * @param  string  $file
     * @return string
     * @throws Upload_Exception
     */
    public function save($path, $file)
    {
        $savefile = $this->_filename($this->_tmp, $this->get_ext($file), self::$level);

        $newfile = IO::strip($path.$savefile);

        if ( ! file_exists($newfile)) // 文件不存在
        {
            $path = dirname($newfile);
            if ( ! IO::mkdir($path)) // 创建目录
            {
                throw new Upload_Exception('无法创建文件上传目录 :path',
                    array(':path' => Debug::path($path)));
            }

            if ( ! @move_uploaded_file($this->_tmp, $newfile))
            {
                throw new Upload_Exception('无法从临时目录复制上传文件');
            }
        }

        return $savefile;
    }

    /**
     * 获取文件存储路径
     *
     * @param  string  $file
     * @param  string  $ext
     * @param  int     $level
     * @return string
     */
    protected function _filename($file, $ext, $level = 2)
    {
        if ( ! is_file($file))
        {
            return '';
        }

        $md5 = md5_file($file);
        $local = 0;
        $savefile = '';
        for ($i = 0; $i < $level; $i++)
        {
            $savefile .= '/'.substr($md5, $local, 2);
            $local += 2;
            if ($local > 30) break; // 文件名长度不足
        }

        return $savefile.'/'.$md5.'.'.$ext;
    }

}